﻿using UnityEngine;
using System.Collections.Generic;


namespace Framework.AssetsManager
{
    public class ABCacheTimer : Singleton<ABCacheTimer>
    {
        private Dictionary<string, ABCache> m_abs = new Dictionary<string, ABCache>();
        private List<string> m_dels = new List<string>();

        public void Process()
        {
            Dictionary<string, ABCache>.Enumerator e = m_abs.GetEnumerator();

            while (e.MoveNext())
            {
                e.Current.Value.passTime += Time.unscaledDeltaTime;

                if (e.Current.Value.passTime >= e.Current.Value.time)
                {
                    if (e.Current.Value.time != 0)
                        m_dels.Add(e.Current.Value.name);
                }
            }

            List<string>.Enumerator d = m_dels.GetEnumerator();

            while (d.MoveNext())
            {
                Remove(d.Current);
            }

            m_dels.Clear();
        }

        private void Remove(string _name)
        {
            ABCache ab;
            if (m_abs.TryGetValue(_name, out ab))
            {
                if (ab != null)
                {
                    if(ab.ab != null)
                        ab.ab.Unload(false);

                    ResManager.Instance.RemoveResource(_name);
                    m_abs.Remove(_name);

                }

            }
        }

        public void AddABCache(ABCache _ab)
        {
            if (m_abs.ContainsKey(_ab.name))
            {
                Debug.LogError("ABCacheTimer has same ABCache, Unloaded new assetbundle");
                _ab.ab.Unload(false);
                return;
            }

            m_abs.Add(_ab.name, _ab);
        }

        public void ResetABTime(string _name)
        {
            ABCache ab;
            if (m_abs.TryGetValue(_name, out ab))
            {
                ab.passTime = 0;
            }
            else
            {
                Debug.Log("This ABTimer is null:" + _name);
            }
        }


    }
}